<template>

  <div class="duty_management">
    <div class="calendar-header">
      <div class="header-left">
        <h1>{{ formatYearMonth(currentMonth) }}</h1>
      </div>
      <div class="header-right">
        <div class="view-selector">
          <span v-for="(item, index) in viewOptions" :key="index"
            :class="['view-item', viewType === item.value ? 'active' : '']" @click="switchView(item.value)">{{
              item.label }}</span>
        </div>
        <el-date-picker v-model="currentMonth" type="month" :clearable="false" placeholder="请选择月份" format="YYYY-MM"
          value-format="YYYY-MM" style="margin-left: 10px; width: 150px;" @change="changeMonth" />
        <el-select v-model="selectedUser" placeholder="全部" style="width: 120px; margin-left: 10px;"
          @change="handleUserChange" filterable>
          <el-option label="全部" value="" />
          <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-button type="primary" class="add-btn" @click="handleAddSchedule()">
          <i class="el-icon-plus"></i> 新增排班
        </el-button>
      </div>
    </div>

    <div v-loading="loading" ref="fullcalendar" class="calendar-container"></div>

    <!-- 新增/编辑排班弹窗 -->
    <el-dialog :title="dialogType === 'add' ? '新增排班' : '编辑排班'" v-model="dialogVisible" width="500px"
      :close-on-click-modal="false" custom-class="schedule-dialog">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker v-model="formData.date" type="date" placeholder="选择日期" style="width: 100%"
            value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-time-picker v-model="formData.time" format="HH:mm" placeholder="选择时间" style="width: 100%" />
        </el-form-item>
        <el-form-item label="用户" prop="userId">
          <el-select v-model="formData.userId" placeholder="请选择用户" style="width: 100%" filterable>
            <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="formData.color" show-alpha :predefine="predefineColors" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, toRefs, ref, onMounted, getCurrentInstance } from 'vue';
import { formatDate } from '@/utils/formatTime';
import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import { createSchedule, getScheduling, getUser } from '@/api/duty';

const { proxy } = getCurrentInstance();
const fullcalendar = ref(null);
const formRef = ref(null);
const predefineColors = ref([
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  'rgba(255, 69, 0, 0.68)',
  'rgb(255, 120, 0)',
  'hsv(51, 100, 98)',
  'hsva(120, 40, 94, 0.5)',
  'hsl(181, 100%, 37%)',
  'hsla(209, 100%, 56%, 0.73)',
  '#c7158577',
])
const state = reactive({
  loading: false,
  currentMonth: new Date().getFullYear() + '-' + String(new Date().getMonth() + 1).padStart(2, '0'),
  viewType: 'month',
  viewOptions: [
    { label: '月', value: 'month' },
    { label: '周', value: 'week' },
    { label: '日', value: 'day' }
  ],
  calendar: null,
  userList: [],
  selectedUser: '',
  scheduleList: [],
  dialogVisible: false,
  dialogType: 'add', // add或edit
  submitLoading: false,
  formData: {
    title: '',
    date: formatDate(new Date()),
    time: new Date(),
    userId: '',
    color: '',
    remark: ''
  },
  rules: {
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    date: [{ required: true, message: '请选择日期', trigger: 'change' }],
    userId: [{ required: true, message: '请选择用户', trigger: 'change' }]
  },
  colorOptions: [
    { value: 'green', bg: '#4caf50', light: '#e8f5e9' },
    { value: 'blue', bg: '#2196f3', light: '#e3f2fd' },
    { value: 'red', bg: '#f44336', light: '#ffebee' },
    { value: 'orange', bg: '#ff9800', light: '#fff3e0' },
    { value: 'purple', bg: '#9c27b0', light: '#f3e5f5' }
  ],

});

onMounted(() => {
  getUserList();
  initCalendar();
});

// 初始化日历
const initCalendar = () => {
  state.calendar = new Calendar(fullcalendar.value, {
    plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
    initialView: 'dayGridMonth',
    headerToolbar: false,
    locale: 'zh-cn',
    firstDay: 1, // 周一为一周的第一天
    height: 'auto',
    dayMaxEvents: 3,
    selectable: true,
    eventTimeFormat: {
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    },
    eventClassNames: function (arg) {
      const colorClass = arg.event.extendedProps.color || 'blue';
      return [`event-${colorClass}`];
    },
    eventContent: function (arg) {
      const timeEl = document.createElement('div');
      const titleEl = document.createElement('div');

      if (arg.event.start) {
        const hours = arg.event.start.getHours().toString().padStart(2, '0');
        const minutes = arg.event.start.getMinutes().toString().padStart(2, '0');
        timeEl.innerHTML = `${hours}:${minutes}`;
        timeEl.className = 'event-time';
      }

      titleEl.innerHTML = arg.event.title;
      titleEl.className = 'event-title';

      const containerEl = document.createElement('div');
      containerEl.className = 'event-container';
      containerEl.appendChild(timeEl);
      containerEl.appendChild(titleEl);

      return { domNodes: [containerEl] };
    },
    dateClick: function (info) {
      handleDateClick(info);
    },
    eventClick: function (info) {
      handleEventClick(info);
    },
    moreLinkContent: function (args) {
      return `+${args.num} 更多`;
    }
  });
  state.calendar.render();

  getScheduleList();
};



// 格式化年月显示
const formatYearMonth = (dateStr) => {
  if (!dateStr) return '';
  const [year, month] = dateStr.split('-');
  return `${year}年${parseInt(month)}月`;
};

// 获取用户列表
const getUserList = () => {
  state.loading = true;
  getUser()
    .then(res => {
      if (res) {
        state.userList = res;
      }
    })
    .catch(err => {
      console.error('获取用户列表失败:', err);
      proxy.$message.error('获取用户列表失败');
    })
    .finally(() => {
      state.loading = false;
    });
};

// 获取排班列表
const getScheduleList = () => {
  state.loading = true;

  // 获取当前视图的日期范围
  const view = state.calendar.view;
  const startDate = formatDate(view.activeStart);
  const endDate = formatDate(view.activeEnd);

  const params = {
    from: startDate,
    to: endDate,
    userId: state.selectedUser || undefined
  };

  // 清除现有事件
  state.calendar.getEventSources().forEach(source => {
    source.remove();
  });

  getScheduling(params)
    .then(res => {
      if (res) {
        // 处理返回的数据
        const events = res.map(item => {
          const user = state.userList.find(user => user.id === item.userId) || {};
          const colors = ['green', 'blue', 'red', 'orange', 'purple'];
          const color = item.color || colors[Math.floor(Math.random() * colors.length)];

          // 解析时间
          let eventDate = new Date(item.date);
          let eventTime = item.time ? item.time.split(':') : [9, 0]; // 默认9:00
          eventDate.setHours(parseInt(eventTime[0]), parseInt(eventTime[1]));

          return {
            id: item.id,
            title: item.title || user.name || '未知用户',
            start: eventDate,
            allDay: !item.time,
            extendedProps: {
              userId: item.userId,
              remark: item.remark,
              color: color
            }
          };
        });

        state.scheduleList = events;
        state.calendar.addEventSource(events);
      } 
    })
    .catch(err => {
      console.error('获取排班列表失败:', err);
      proxy.$message.error('获取排班列表失败');
    })
    .finally(() => {
      state.loading = false;
    });
};

// 点击日期添加排班
const handleDateClick = (info) => {
  const clickDate = new Date(info.dateStr);
  const hours = new Date().getHours();
  const minutes = Math.floor(new Date().getMinutes() / 30) * 30;

  clickDate.setHours(hours, minutes);

  state.dialogType = 'add';
  state.formData = {
    title: '',
    date: info.dateStr,
    time: clickDate,
    userId: state.userList.length > 0 ? state.userList[0].id : '',
    color: 'blue',
    remark: ''
  };
  state.dialogVisible = true;
};

// 点击事件查看/编辑排班
const handleEventClick = (info) => {
  const event = info.event;
  const startDate = event.start;

  state.dialogType = 'edit';
  state.formData = {
    id: event.id,
    title: event.title,
    date: formatDate(startDate),
    time: startDate,
    userId: event.extendedProps.userId,
    color: event.extendedProps.color || 'blue',
    remark: event.extendedProps.remark || ''
  };
  state.dialogVisible = true;
};

// 新增排班
const handleAddSchedule = () => {
  const now = new Date();

  state.dialogType = 'add';
  state.formData = {
    title: '',
    date: formatDate(now),
    time: now,
    userId: state.userList.length > 0 ? state.userList[0].id : '',
    color: 'blue',
    remark: ''
  };
  state.dialogVisible = true;
};

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      state.submitLoading = true;

      // 格式化时间
      const timeStr = state.formData.time ?
        `${state.formData.time.getHours().toString().padStart(2, '0')}:${state.formData.time.getMinutes().toString().padStart(2, '0')}` :
        '';

      const params = {
        ...state.formData,
        time: timeStr
      };

      createSchedule(params)
        .then(res => {
          if (res) {
            proxy.$message.success(state.dialogType === 'add' ? '新增排班成功' : '编辑排班成功');
            state.dialogVisible = false;
            getScheduleList();
          }
        })
        .catch(err => {
          console.error('保存排班失败:', err);
          proxy.$message.error('保存排班失败');
        })
        .finally(() => {
          state.submitLoading = false;
        });
    }
  });
};

// 切换月份
const changeMonth = (date) => {
  if (!date) return;

  const [year, month] = date.split('-');
  const newDate = new Date(parseInt(year), parseInt(month) - 1, 1);
  state.calendar.gotoDate(newDate);

  getScheduleList();
};

// 切换视图类型
const switchView = (viewType) => {
  state.viewType = viewType;

  if (viewType === 'month') {
    state.calendar.changeView('dayGridMonth');
  } else if (viewType === 'week') {
    state.calendar.changeView('timeGridWeek');
  } else if (viewType === 'day') {
    state.calendar.changeView('timeGridDay');
  }

  getScheduleList();
};

// 切换用户
const handleUserChange = () => {
  getScheduleList();
};

const { calendar, scheduleList, userList, loading, dialogVisible, dialogType, formData, submitLoading, viewType,currentMonth,viewOptions,selectedUser } =   toRefs(state);

</script>

<style lang="scss" scoped>
.duty_management {
  background-color: #fff;
  margin: 20px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .calendar-header {
    margin: 0 0 24px 0;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    h1 {
      font-size: 24px;
      font-weight: 500;
      line-height: 32px;
      margin: 0;
      color: #262626;
    }

    .header-right {
      display: flex;
      align-items: center;

      .view-selector {
        display: flex;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        overflow: hidden;

        .view-item {
          padding: 6px 12px;
          font-size: 13px;
          cursor: pointer;
          color: #606266;
          background-color: #f5f7fa;
          border-right: 1px solid #dcdfe6;
          transition: all 0.3s;

          &:last-child {
            border-right: none;
          }

          &.active {
            color: #fff;
            background-color: #409EFF;
          }

          &:hover:not(.active) {
            background-color: #e6e6e6;
          }
        }
      }

      .add-btn {
        margin-left: 15px;
        background-color: #1890ff;
        border-color: #1890ff;

        &:hover,
        &:focus {
          background-color: #40a9ff;
          border-color: #40a9ff;
        }
      }
    }
  }

  .calendar-container {
    min-height: 700px;

    :deep(.fc) {
      .fc-daygrid-day.fc-day-today {
        background-color: rgba(24, 144, 255, 0.05);
      }

      .fc-daygrid-day-top {
        padding: 8px;
        justify-content: flex-start;
      }

      .fc-daygrid-day-number {
        font-size: 16px;
        font-weight: 500;
        color: #262626;
      }

      .fc-col-header {
        background-color: #fafafa;
      }

      .fc-col-header-cell {
        padding: 12px 0;
      }

      .fc-col-header-cell-cushion {
        font-weight: 500;
        color: #262626;
        font-size: 14px;
      }

      .fc-theme-standard td,
      .fc-theme-standard th {
        border: 1px solid #f0f0f0;
      }

      .fc-day-other .fc-daygrid-day-top {
        opacity: 0.5;
      }

      .fc-more-link {
        color: #1890ff;
        font-size: 12px;
        font-weight: 500;
        margin-top: 4px;

        &:hover {
          text-decoration: underline;
        }
      }

      .event-container {
        padding: 4px 8px;
        border-radius: 4px;
        overflow: hidden;
        margin-bottom: 2px;

        .event-time {
          font-size: 12px;
          font-weight: 500;
          margin-right: 4px;
          display: inline-block;
        }

        .event-title {
          font-size: 12px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          display: inline-block;
        }
      }

      .event-green {
        background-color: #e8f5e9;
        border-left: 3px solid #4caf50;
        color: #1b5e20;
      }

      .event-blue {
        background-color: #e3f2fd;
        border-left: 3px solid #2196f3;
        color: #0d47a1;
      }

      .event-red {
        background-color: #ffebee;
        border-left: 3px solid #f44336;
        color: #b71c1c;
      }

      .event-orange {
        background-color: #fff3e0;
        border-left: 3px solid #ff9800;
        color: #e65100;
      }

      .event-purple {
        background-color: #f3e5f5;
        border-left: 3px solid #9c27b0;
        color: #4a148c;
      }
    }
  }
}

.color-selector {
  display: flex;
  gap: 12px;

  .color-item {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    cursor: pointer;
    transition: all 0.3s;
    position: relative;

    &:hover {
      transform: scale(1.1);
    }

    &.selected {
      box-shadow: 0 0 0 2px #fff, 0 0 0 4px #1890ff;

      &:after {
        content: '';
        position: absolute;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #fff;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
  }
}
</style>

<style>
.schedule-dialog .el-dialog__body {
  padding-top: 10px;
}
</style>